<template>
  <div class="wrapper pb-3 h-100" style="padding:20px 0;overflow-x: auto">
    <div class="d-flex" id="box" style="min-width: 1325px;">
      <div class="mb-3 d-flex align-items-center" >
        <!--<el-input placeholder="请输入内容" class="input-with-select w350" size="small" clearable v-model="search">-->
          <!--<el-select class="w130" v-model="selectType" slot="prepend" placeholder="请选择">-->
            <!--<el-option label="控制箱" value="1"></el-option>-->
            <!--<el-option label="RTU单灯分组" value="2"></el-option>-->
            <!--<el-option label="NB单灯分组" value="3"></el-option>-->
          <!--</el-select>-->
          <!--<el-button slot="append" class="ur-btn ur-btn-primary" @click="QueryLightMonitor"><i class="iconfont icon-sousuo"></i>查询</el-button>-->
        <!--</el-input>-->
        责任区：
        <el-select class="w120 mr-2" v-model="pole.regionId" slot="prepend" placeholder="请选择" size="small">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in regions" :key="index" :label="item.Name" :value="item.Id"></el-option>
        </el-select>
        控制器类型：
        <el-select class="w100 mr-2" v-model="pole.channelMode" slot="prepend" placeholder="请选择" size="small" @change="queryGroup">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in global.TnChannelModes" :key='index+1' :label="item.name" :value="item.id"></el-option>
        </el-select>
        分组：
        <el-select class="w140 mr-2" v-model="pole.groupId" slot="prepend" placeholder="请选择" size="small" @change="selectGroup">
          <el-option label="全部" :value="-1"></el-option>
          <el-option v-for="(item,index) in groups" :key="index" :label="item.GroupName+'('+item.typeName+')'" :value="item.Id"></el-option>
        </el-select>
        <el-input placeholder="请输入内容"  class="input-with-select w180 mr-2"  size="small" v-model="pole.value">
          <el-button v-if="limits.indexOf('2_05_02_01')!=-1" slot="append"  class="ur-btn ur-btn-primary" @click="currentPage=1;pole.qtype=null;QueryLightMonitor()">查询</el-button>
        </el-input>
        <el-button v-if="limits.indexOf('2_05_02_03')!=-1||limits.indexOf('2_05_02_08')!=-1" class="ur-btn ur-btn-primary" @click="clearAlarm">清除报警</el-button>
        <el-button v-if="limits.indexOf('2_05_02_14')!=-1" class="ur-btn ur-btn-primary ml-2" @click="exportData">导出</el-button>
      </div>
      <ul class="result_group ml-auto">
        <li @click="pole.qtype=1;QueryLightMonitor()"><i class="circle error"></i>报警：{{count.AlarmCount}}</li>
        <li @click="pole.qtype=3;QueryLightMonitor()"><i class="circle success"></i>在线：{{count.OnLineCount}}</li>
        <li @click="pole.qtype=2;QueryLightMonitor()"><i class="circle Violet"></i>离线：{{count.OffLineCount}}</li>
        <li style="cursor: default"><i class="circle orange"></i>开灯：{{count.OnStateCount}}</li>
        <li style="cursor: default"><i class="circle ash"></i>关灯：{{count.OffStateCount}}</li>
      </ul>
    </div>
    <el-table ref="lightTable" :data="tableData3" tooltip-effect="dark" style="min-width: 1325px;margin:0 0 10px" :height="clientHeight-205" highlight-current-row  @selection-change="selsChange" @cell-click="alarmFun" :cell-class-name="api.fixedCell">
      <el-table-column type="selection" width="40" align="center" fixed></el-table-column>
      <el-table-column align="center" type="index" :index="indexMethod" label="序号" width="50" fixed></el-table-column>
      <el-table-column prop="PoleNo" label="灯杆编号" align="center" width="100" fixed></el-table-column>
      <el-table-column prop="BoxNo" label="所属控制箱" align="center" min-width="120" fixed></el-table-column>
      <el-table-column prop="PoleDevAddr" label="设备地址" width="160" align="center" fixed></el-table-column>
      <el-table-column prop="ChannelMode" label="通讯模式" width="100" align="center">
        <template slot-scope="scope" >
          <template v-for="(item,index) in global.TnChannelModes" v-if="item.id==scope.row.ChannelMode">
            {{item.name+(scope.row.ChannelMode==2?scope.row.SimOprators:'')}}
          </template>
        </template>
      </el-table-column>
      <!--<el-table-column prop="AreaName" label="责任区" min-width="120" align="center"></el-table-column>-->
      <el-table-column prop="RoadSection" label="所属路段" min-width="120" align="center"></el-table-column>
      <el-table-column prop="LastUpdateTime" label="记录时间" width="160" align="center"></el-table-column>
      <el-table-column prop="" label="告警状态" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.IsAlarm==0">
            <i class="circle blue"></i>正常
          </template>
<!--          <template v-else ><i class="circle error"></i>报警</template>-->
          <div v-else class="d-flex align-items-center justify-content-end">
            <i class="" :class="alarmClass(scope.row).class" :title="alarmClass(scope.row).txt"></i>报警
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" label="运行状态" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.RunState==0">
            <i class="circle success"></i>正常
          </template>
          <template v-else>
            <i class="circle yellow"></i>故障
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="" label="在线状态" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.Online==0">
            <i class="circle Violet"></i>离线
          </template>
          <template v-else>
            <i class="circle  success"></i>在线
          </template>
        </template>
      </el-table-column>
      <el-table-column prop="" label="火1" min-width="60" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.State1==0">
            <i class="circle ash"></i>关
          </template>
          <template v-else-if="scope.row.State1==1">
            <i class="circle  orange"></i>开
          </template>
          <template v-else></template>
        </template>
      </el-table-column>
      <el-table-column prop="" label="火2" min-width="60" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.State2==1">
            <i class="circle orange"></i>开
          </template>
          <template v-else-if="scope.row.State2==0">
            <i class="circle ash"></i>关
          </template>
          <template v-else></template>
        </template>
      </el-table-column>
      <el-table-column prop="" label="火3" min-width="60" align="center">
        <template slot-scope="scope">
          <template v-if="scope.row.State3==1">
            <i class="circle orange"></i>开
          </template>
          <template v-else-if="scope.row.State3==0">
            <i class="circle ash"></i>关
          </template>
          <template v-else></template>
        </template>
      </el-table-column>
      <el-table-column label="详情" width="240" align="center">
        <template slot-scope="scope">
          <el-button v-if="limits.indexOf('2_05_02_04')!=-1||limits.indexOf('2_05_02_10')!=-1" round class="ur-btn-round float-left " @click="look(scope.row,'nbhisroty')">
            <i class="iconfont icon-lishijilu txt_blue4"></i>历史</el-button>
          <el-button v-if="limits.indexOf('2_05_02_05')!=-1" round class="ur-btn-round float-left ml-1" @click="look(scope.row,'detail')">
            <i class="iconfont icon-xianshi txt_blue4"></i>实时</el-button>
          <el-button v-if="limits.indexOf('2_10_00_03')!=-1" round class="ur-btn-round ml-1" @click="look(scope.row,'smsConfig')">短信设置</el-button>
        </template>
      </el-table-column>
      <el-table-column label="电能" align="center">
        <template slot-scope="scope">
          <el-button v-if="limits.indexOf('2_05_02_06')!=-1||limits.indexOf('2_05_02_09')!=-1" round class="ur-btn-round" @click="look(scope.row,'energy')"><i class="iconfont icon-dianliangtongji txt_orange"></i>查看</el-button>
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" align="center" width="90">
        <template slot-scope="scope">
          <template v-if="scope.row.Operation==1">
            <el-button round class="ur-btn-round" @click="order(scope.$index,scope.row)"><i class="iconfont icon-anzhuangweihu blue1"></i>工单</el-button>
          </template>
          <template v-else-if="scope.row.Operation==2">
            已派工
          </template>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination class="float-right" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
    :page-sizes="[100,200,500,1000]" :page-size="pageSize" layout="total,sizes, prev, pager,next,jumper" :total="total">
    </el-pagination>
    <el-dialog v-el-drag-dialog title="查看详情" :visible.sync="detailDig" width="540px" style="margin-top:11vh;" center @close="closeDetailDialog(false)">
      <template v-if="detailDig">
        <lightlistdetails @closeDetailDialog="closeDetailDialog($event)" :pole="data"></lightlistdetails>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="生成工单" :visible.sync="workDig" width="750px" style="margin-top:11vh;" center @close="closeWorkDialog(false)">
      <template v-if="workDig">
        <lightlistwork @closeWorkDialog="closeWorkDialog($event)"  @WorkDialog="WorkDialog($event)" :areas="regions" :data="data"></lightlistwork>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="历史电能" :visible.sync="energyDig" width="750px" style="margin-top:11vh;"  @close="energyDig=false">
      <template v-if="energyDig">
        <light-energy :pole="data"></light-energy>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="历史信息" :visible.sync="nbLightInfoDig" width="900px"   @close="nbLightInfoDig=false">
      <template v-if="nbLightInfoDig">
        <nb-light-history :pole="data"></nb-light-history>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog title="历史报警详情" :visible.sync="alarmDig" width="840px"  style="margin-top:11vh;" @close="alarmDig=false">
      <template v-if="alarmDig">
        <rtulistalarm @closealarmDialog="alarmDig=false"  :data="data" :type="2"></rtulistalarm>
      </template>
    </el-dialog>

    <el-dialog v-el-drag-dialog :title="data.BoxNo+'——短信配置'" :visible.sync="showSMSConfig" width="700px" top="6%"  @close="closeSmsConfig">
      <template v-if="showSMSConfig">
        <sms-push-config :boxs="sels" ></sms-push-config>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import elDragDialog from 'directive/el-dragDialog'
  import lightlistdetails from './light-list-details'
  import lightlistwork from './light-list-work'
  import rtulistalarm from './rtu-list-alarm'
  import lightEnergy from './light-energy-statistics'
  import api from 'api/api'
  import {mapState} from 'vuex'
  import fetch from 'api/fetch'
  import smsPushConfig from './sms-push-config'

  export default {
    directives:{elDragDialog},
    components: {
      lightlistdetails,
      lightlistwork,
      lightEnergy,
      rtulistalarm,smsPushConfig
    },
    props: {},
    data() {
      return {
        detailDig: false,
        workDig: false,
        energyDig:false,
        nbLightInfoDig:false,
        alarmDig:false,
        total: 0,
        currentPage: 1,
        pageSize:100,
        tableData3: [],
        data: "",
        tableIndex: "",
        count:{AlarmCount:0,OffLineCount:0,OnLineCount:0,OnStateCount:0,OffStateCount:0},
        sels:[],
        regions:[],
        groups:[],
        pole:{regionId:-1,channelMode:-1,groupId:-1,value:''},
        timer:null,
        api:api,
        showSMSConfig:false
      }
    },
    watch: {
      pole:{
        handler(newVal,oldVal){
          this.currentPage=1
        },
        deep:true
      }
    },
    computed:mapState({
      clientHeight: state => state.comm.clientHeight,
      clientWidth: state => state.comm.clientWidth,
      limits:state=>state.user.userInfo.limits
    }),
    methods: {
      closeSmsConfig(){
        this.showSMSConfig=false
        this.sels=[]
      },
      exportData(){
        api.fetchFile('/Monitor/ExportLightMonitor', this.pole)
          .then(r => {
            fetch.saveFile(r,'单灯监控列表',['',''])
          })
      },
      alarmFun(row,column,cell){
        if (row.IsAlarm == 1 && column.label == "告警状态") {
          this.data = row
          this.alarmDig = true
        }
      },
      selectGroup(id){
        this.groups.map(r=>{
          if (r.Type == 2) {
            this.$set(this.pole, 'channelMode', 1)
          } else if (r.Type == 3) {
            this.$set(this.pole, 'channelMode', 2)
          }
        })
      },
      clearAlarm() {
        if (this.sels.length) {
          if(this.limits.indexOf('2_05_02_03')==-1) return this.$message.error('该用户无权限操作')
          this.$confirm('确定删除勾选单灯报警？', '提示', {type: 'warning'})
            .then(() => {
              this.sels.map(r => {
                api.fetchSimple('/Monitor/ClearLightAlarmById', {tnId: r.TnId})
                    .then(r=>{
                      if(r!=''){
                        this.$refs.lightTable.clearSelection()//清空选择
                      }
                    })
              })
            })
        } else {
          if(this.limits.indexOf('2_05_02_08')==-1) return this.$message.error('该用户无权限操作')
          this.$confirm('确定删除所有单灯报警？', '提示', {type: 'warning'})
            .then(() => {
              api.fetchSimple('/Monitor/ClearAllLightAlarm', {})
            })
        }
      },
      selsChange(sels){
        this.sels=sels
      },
      indexMethod(index) {
        return index + 1;
      },
      closeDetailDialog(v) {
        this.detailDig = false
      },
      closeWorkDialog(v) {
        this.workDig = false;
      },
      look(data,type) {
        this.data = data
        debugger
        if( type == 'detail'){
          if(data.Online==0){
            return this.$message.warning({showClose:true,message:'不在线'})
          }
          this.detailDig = true
        }else if(type=='nbhisroty'){
          this.nbLightInfoDig=true
        }else if(type=='smsConfig'){
          this.sels=[data]
          this.showSMSConfig=true
        }else{
          this.energyDig = true
        }
      },
      order(index, data) {
        this.tableIndex = index;
        this.data = data;
        this.workDig = true;
      },
      WorkDialog(v) {
        if (v) {
          this.tableData3[this.tableIndex].Operation = 2
        }
      },
      //单灯监控
      QueryLightMonitor() {
        let pole = Object.assign({}, this.pole)
        pole = Object.assign(pole, {pageNo: this.currentPage, pageSize: this.pageSize, onlyState: 0})
        api.fetchSimple('/Monitor/QueryLightMonitor', pole).then(r => {
          if (!r.data){
            this.total=0
            this.tableData3=[]
            return
          }
          this.total = r.total||0
          if(this.tableData3.length!=r.data.length){
            this.tableData3 = r.data
          }else{
            (r.data).map((pole,index,arr)=>{
              for(let key in pole){
                this.tableData3[index][key]=pole[key]
              }
            })
          }
        })
      },
      LightMonitorStatistics() {
        api.fetchSimple('/Monitor/LightMonitorStatistics',this.pole).then(r => {
          this.count=r.data
        })
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.currentPage = 1;
        this.QueryLightMonitor()
      },
      handleCurrentChange(val) {
        this.currentPage = val;
        this.QueryLightMonitor()
      },
      queryRegion(){
        fetch.queryArea()
          .then(r=>{
            this.regions=r.data
          })
      },
      queryGroup(){
        this.groups=[]
        fetch.queryGroup()
          .then(r=>{
            r.data.map(r=>{
              if(r.Type==2&&(this.pole.channelMode==1||this.pole.channelMode==-1)){
                this.groups.push(Object.assign(r,{typeName:'RTU'}))
              }else if(r.Type==3&&(this.pole.channelMode==2||this.pole.channelMode==-1)){
                this.groups.push(Object.assign(r,{typeName:'NB'}))
              }
            })
          })
      },
      alarmClass(row){
        if(row.IsAlarm==1){
          let ercs=Object.keys(JSON.parse(row.Ercs))
          if(ercs.includes('200')){
            return {class:'alarmIcon erc70',txt:'关灯异常'}
          }else {
            return {class:'circle error',txt:'报警'}
          }
        }
      },
    },
    created() {
      let self = this;
      this.queryRegion()
      this.queryGroup()
      this.QueryLightMonitor()
      this.LightMonitorStatistics()
      this.timer = setInterval(function () {
        self.QueryLightMonitor()
        self.LightMonitorStatistics()
      }, 3000)
      // this.$once('hook:beforeDestroy', () => {
      //   clearInterval(xxx);
      // })
    },
    mounted() {
    },
    beforeRouteLeave(to, from, next){
      clearInterval(this.timer)
      this.timer=null
      next()
    }
  }
</script>
<style scoped lang="stylus" rel="stylesheet/stylus">
  .Violet {background: #9CB0C6}
  .blue {background: #0c8eec}
  .blue1 {color: #0c8eec}
  .orange{background:#FFa100}
  .ash {background: #6e6e6e}
  .yellow {background:yellow}

</style>
